<?php

namespace lvzmen\yii\cms\widgets\sidebar;


use Yii;
use yii\base\Widget;
use yii\web\View;
use \lvzmen\yii\cms\assets\ztree\ZtreeAsset;

/**
 * A menu imitate the sidebar of https://docs.docker.com/get-started/
 *
 * @note It's depend on bootstrap;
 *
 * @example :
 * ```php
 * \lvzmen\yii\cms\widgets\sidebar\Sidebar::widget([
 *     "nodes" => [
 *         ["name" => "概述", "open" => true, "page" => "overview"],
 *         ["name" => "Botton", "open" => false, "children" => [
 *             ["name" => "Button Group", "open" => false]
 *         ]],
 *         ["name" => "Botton", "open" => false, "children" => [
 *             ["name" => "Button Group", "open" => false]
 *         ]],
 *         ["name" => "Botton", "open" => false, "children" => [
 *             ["name" => "Button Group", "open" => false]
 *         ]],
 *         ["name" => "Botton", "open" => false, "children" => [
 *             ["name" => "Button Group", "open" => false]
 *         ]],
 *     ],
 *     "onclick" => <<<JS
 *     $.ajax({
 *         type: "POST",
 *         url: "/yii2/home",
 *         data: {page: treeNode.page},
 *         dataType: "text",
 *         success: function(res){
 *             $(".cms-article").html(res);
 *         }
 *     });
 * JS
 * ])
 * ```
 * @author chenzhiwei <chenzhiweiwk@qq.com>
 * @date   2021/08/31
 */
class Sidebar extends Widget
{
    public $id;
    public $nodes;
    public $onclick = "";
    public $class = "cms-sidebar col-md-2";

    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub

        ZtreeAsset::register($this->getView());

        $this->id = $this->id ?? "sidebar" . time();
        $this->nodes = json_encode(is_array($this->nodes) ? $this->nodes : [
            ["name" => "level1", "open" => true, "children" => [
                ["name" => "level2", "open" => true]
            ]]
        ]);
        $this->addCss();
        $this->addJs();
    }

    public function run()
    {
        return "<div class='{$this->class}'><ul id='{$this->id}' class='ztree'></ul></div>";
    }


    public function addCss(){
        $css = <<<CSS
.cms-sidebar {
    position: fixed;
    top: 60px;
    left:0;
    overflow: auto;
    max-height: calc(100vh - 50px);
    padding-top: 0px;
    padding-bottom: 20px;
    width: 200px;
}
.curSelectedNode .node_name {
    color: #FE7300;
}
CSS;
        $this->view->registerCss($css);
    }

    public function addJs(){
        $js = <<<JS
var setting = {
    callback: {
        onClick: function (event, treeId, treeNode) {
            {$this->onclick}
        },
    }
};
var zNodes = {$this->nodes};
var zTreeObj = $.fn.zTree.init($("#{$this->id}"), setting, zNodes);
console.info(zTreeObj.getNodes());
$.each(zTreeObj.getNodes(), function(k,v){
    console.info(v.active);
    if(v.active == true) {
        $("#" + v.tId + "_a").trigger('click');
    } 
});
JS;
        $this->view->registerjS($js, View::POS_READY);
    }
}
